package com.atguigu.tingshu.user.listener;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.tingshu.common.constant.RabbitConstant;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.model.order.OrderDetail;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.model.user.UserPaidAlbum;
import com.atguigu.tingshu.model.user.UserPaidTrack;
import com.atguigu.tingshu.model.user.UserVipService;
import com.atguigu.tingshu.user.mapper.UserInfoMapper;
import com.atguigu.tingshu.user.mapper.UserPaidAlbumMapper;
import com.atguigu.tingshu.user.mapper.UserPaidTrackMapper;
import com.atguigu.tingshu.user.mapper.UserVipServiceMapper;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.joda.time.DateTime;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
@Slf4j
public class UserMqListener {
    @Autowired
    UserVipServiceMapper userVipServiceMapper;
    @Autowired
    UserInfoMapper userInfoMapper;
    @Autowired
    UserPaidAlbumMapper userPaidAlbumMapper;
    @Autowired
    UserPaidTrackMapper userPaidTrackMapper;
    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue(value = RabbitConstant.PAYMENT_REFUND_QUEUE , durable = "true"),
                    exchange = @Exchange(value = RabbitConstant.PAYMENT_EXCHANGE , type = "topic"),
                    key = {RabbitConstant.PAYMENT_STATE_RK}
            )
    })
    @SneakyThrows
    public void refundDeletePaidRecords(Channel channel , Message message ,
                                  Map<String,String> map){

        try {
            if(!CollectionUtils.isEmpty(map)){
                //删除退款的交易记录
                String itemType = map.get("itemType");
                String orderNo = map.get("orderNo");
                String status = map.get("status");
                if(!status.equals(SystemConstant.PAYMENT_STATUS_REFUND)){
                    channel.basicAck(message.getMessageProperties().getDeliveryTag() , false);
                    return;
                }
                //删除退款记录的业务
                switch (itemType){
                    case SystemConstant.ORDER_ITEM_TYPE_VIP:
                        //1、删除vip退款
                        UserVipService userVipService = userVipServiceMapper.selectOne(Wrappers.lambdaQuery(UserVipService.class)
                                .eq(UserVipService::getOrderNo, orderNo));
                        if(userVipService==null){
                            throw new GuiguException(ResultCodeEnum.DATA_ERROR);
                        }
                        //计算vip的时间，使用用户表中中的vip结束时间减去 vip续期时间
                        long vipDays = (userVipService.getExpireTime().getTime() -
                                userVipService.getStartTime().getTime())/(1000*60*60*24);
                        if(vipDays>0){
                            UserInfo userInfo = userInfoMapper.selectById(userVipService.getUserId());
                            if(userInfo==null){
                                throw new GuiguException(ResultCodeEnum.DATA_ERROR);
                            }
                            DateTime dateTime = new DateTime(userVipService.getExpireTime()).minusDays((int) vipDays);
//                            userVipService.setExpireTime(dateTime.toDate());
                            if(dateTime.toDate().before(new Date())){
                                userInfo.setIsVip(0);//更新vip状态
                            }
                            userInfo.setVipExpireTime(dateTime.toDate());//更新vip过期时间
                            userInfoMapper.updateById(userInfo);
//
                        }
                        userVipServiceMapper.deleteById(userVipService.getId());//删除vip的购买记录
                        break;
                    case SystemConstant.ORDER_ITEM_TYPE_ALBUM:
                        //2、删除专辑退款
//                        UserPaidAlbum userPaidAlbum = userPaidAlbumMapper.selectOne(Wrappers.lambdaQuery(UserPaidAlbum.class)
//                                .eq(UserPaidAlbum::getOrderNo, orderNo));
                        userPaidAlbumMapper.delete(Wrappers.lambdaQuery(UserPaidAlbum.class)
                                .eq(UserPaidAlbum::getOrderNo , orderNo));
//                        userPaidTrackMapper.selectList()
                        userPaidTrackMapper.delete(Wrappers.lambdaQuery(UserPaidTrack.class)
                                .eq(UserPaidTrack::getOrderNo , orderNo));

                        break;
                    case SystemConstant.ORDER_ITEM_TYPE_TRACK:
                        //3、删除声音退款
                        userPaidTrackMapper.delete(Wrappers.lambdaQuery(UserPaidTrack.class)
                                .eq(UserPaidTrack::getOrderNo , orderNo));
                        break;
                }
            }






            channel.basicAck(message.getMessageProperties().getDeliveryTag() , false);
        } catch (Exception e) {
            if(message.getMessageProperties().isRedelivered()){
                log.error("订单支付状态更新失败，消息内容：{}" , JSONObject.toJSONString(map));
                log.error(ExceptionUtils.getStackTrace(e));
                channel.basicReject(message.getMessageProperties().getDeliveryTag() , false);
            }else{
                log.warn("订单支付状态更新失败，尝试重试，消息内容：{}" , JSONObject.toJSONString(map));
                channel.basicNack(message.getMessageProperties().getDeliveryTag() , false,true);
            }
        }


    }

}
